import React, { Component } from 'react';
import { Button, Input, Modal, Form } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import { apiMarketingCutpriceBlacklistPage, apiAddCutPriceBlacklist, apiGetConfigPlatformSet,apiGetConfigPlatformSetEdit } from '@/request/marketingTool'
import { getDateTime3 } from '@/utils/getDate'
import './style.scss'
import _ from 'lodash'

const { TextArea } = Input
export default class Bargain extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef()
    this.formRef = React.createRef()
    this.addFormRef = React.createRef()
    this.state = {
      columns: [
        {
          title: "用户ID",
          dataIndex: "memberId",
          key: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        {
          title: "手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
        },
        {
          title: "砍价次数",
          dataIndex: "cutPriceCount",
          key: "cutPriceCount",
          sorter: {
            // compare: (a, b) => a.cutPriceCount - b.cutPriceCount,
            multiple: 2,
          },
        },
        {
          title: "首次砍价时间",
          dataIndex: "firstCutPriceTime",
          key: "firstHelpCutPriceTime",
          render: (text, record) => {
            return record.firstCutPriceTime ? record.firstCutPriceTime : "/"
          }
        },
        {
          title: "上次砍价时间",
          dataIndex: "lastCutPriceTime",
          key: "lastCutPriceTime",
          render: (text, record) => {
            return record.lastCutPriceTime ? record.lastCutPriceTime : "/"
          }
        },
        {
          title: "帮砍次数",
          dataIndex: "helpCutPriceCount",
          key: "helpCutPriceCount",
          sorter: {
            // compare: (a, b) => a.helpCutPriceCount - b.helpCutPriceCount,
            multiple: 1,
          },
        },
        {
          title: "首次帮砍时间",
          dataIndex: "firstHelpCutPriceTime",
          key: "firstHelpCutPriceTime",
          render: (text, record) => {
            return record.firstHelpCutPriceTime ? record.firstHelpCutPriceTime : "/"
          }
        },
        {
          title: "上次帮砍时间",
          dataIndex: "lastHelpCutPriceTime",
          key: "lastHelpCutPriceTime",
          render: (text, record) => {
            return record.lastHelpCutPriceTime ? record.lastHelpCutPriceTime : "/"
          }
        },
        {
          title: "用户状态",
          dataIndex: "status",
          key: "status",
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'Y':
                label = '黑名单'
                break;
              case 'N':
                label = '正常'
                break;
              case null:
                label = '正常'
                break;
            }
            return label


          }
        },
        {
          title: "操作人",
          dataIndex: "updateUser",
          key: "updateUser",
          render: (text, record) => {
            return record.updateUser ? record.updateUser : "/"
          }
        },
        {
          title: "备注",
          dataIndex: "blacklistRemark",
          key: "blacklistRemark",
          render: (text, record) => {
            return record.blacklistRemark ? record.blacklistRemark : "/"
          }
        },
        {
          title: "操作时间",
          dataIndex: "updateTime",
          key: "updateTime",
          render: (text, record) => {
            return record.updateTime ? record.updateTime : "/"
          }
        },
        {
          title: "操作",
          width: 200,
          fixed: 'right',
          render: (text, render) => {
            return (
              <div>
                {(render.status == 'N' || render.status == null) && <TheButton haspermi={['marketingTool:bargainBlackList:add']} onClick={() => this.add(render.memberId)}>加入黑名单</TheButton>}

                {render.status == 'Y' && <TheButton haspermi={['marketingTool:bargainBlackList:del']} onClick={() => this.del(render.memberId)}>移除黑名单</TheButton>}
              </div>
            );
          },
        },
      ],
      dataSource: [],
      memberId: '',
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      isModalVisible: false,
      isModalOpen: false,
      searchValue: {},
      newColumns: [],
      form_show: true,
      searchOption: [
        { field: 'nickName', label: '用户昵称', placeholder: '用户昵称', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'memberMobile', label: '手机号', placeholder: '手机号', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
        {
          field: 'status', label: '用户状态', placeholder: '请选择用户状态', required: false, rules: [], type: 'Select', options: [
            { value: '2', label: '正常' },
            { value: '1', label: '黑名单' },
          ], defaultValue: ''
        },
        {
          field: 'cutStatus', label: '砍价状态', placeholder: '请选择砍价状态', required: false, rules: [], type: 'Select', options: [
            { value: '1', label: '砍价中' },
            { value: '2', label: '砍价成功' },
            { value: '3', label: '下单' },
            { value: '4', label: '失败' },
            { value: '5', label: '失效' },
          ], defaultValue: ''
        },
        { field: 'time', label: '申请时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
      ],
      queryForm: {},
      sort: []
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    this.getData()
  }
  getData(values) {
    let { pageNo, pageSize } = this.state.pageData
    if (values && !_.isEmpty(values.time)) {
      values.startTime = getDateTime3(values.time[0])
      values.endTime = getDateTime3(values.time[1])
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      let { time, ...form } = { ...this.state.queryForm }
      const res = await apiMarketingCutpriceBlacklistPage({ sort:this.state.sort.toString(), pageNo, pageSize, ...form })
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          total: res.totalCount
        })
      }
    })
  }
  // 难度配置
  hardSetting = async () => {
    this.setState({
      isModalOpen: true,
    })
    const res = await apiGetConfigPlatformSet({platformSetId: '56'})
    if(res.code === 0){
        this.addFormRef.current.setFieldsValue({
          platformSetShowValue: res.data.platformSetShowValue
        })
    }
  }
  settingOk = async () => {
    const values = this.addFormRef.current.getFieldsValue()
    const res = await apiGetConfigPlatformSetEdit({ ...values, platformSetId: '56' })
    if (res.code === 0) {
      this.settingCancel()
      this.getData()
    }
  }
  // 关闭弹出框
  settingCancel = () => {
    this.addFormRef.current.resetFields()
    this.setState({
      isModalOpen: false
    })
  };
  // 移除黑名单
  del = (res) => {
    console.log(res);
    React.$confirm({
      title: "您确认将该用户移除黑名单？",
      onOk: async () => {
        await apiAddCutPriceBlacklist({ memberId: res }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '移除成功'
              })
            }
          }
        )
        this.getData()
      },
    });
  }
  // 加入黑名单
  add = (res) => {
    this.setState({
      isModalVisible: true,
      memberId: res,
    })
  }
  handleOk = async () => {
    const values = this.formRef.current.getFieldsValue()
    const memberId = this.state.memberId
    const res = await apiAddCutPriceBlacklist({ ...values, memberId })
    if (res.code === 0) {
      this.handleCancel()
      this.getData()
    }
  }
  // 关闭弹出框
  handleCancel = () => {
    this.formRef.current.resetFields()
    this.setState({
      isModalVisible: false,
      isModalOpen: false
    })
  };

  // 分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  }
  // table内容列表更新
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  // 重置
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  // 表格排序
  handleTableChange = (pagination, filters, sorter) => {
    // console.log(pagination, filters, sorter)
    let parms = this.state.sort;
    if (Array.isArray(sorter)){
      sorter.map((item)=>{
        if (item.columnKey == "cutPriceCount"){
          parms[0] = `cutPriceCount${item.order == "ascend"?'':' desc'}`;
        }
        if (item.columnKey == "helpCutPriceCount"){
          parms[1] = `helpCutPriceCount${item.order == "ascend"?'':' desc'}`;
        }
      })
    }
    else{
      if (sorter.order == "ascend"){
        parms = `${sorter.columnKey}`
      }
      else if(sorter.order == "descend"){
        parms = `${sorter.columnKey} desc`
      }
      else {
        parms = ''
      }
      parms = [parms]
    }
    // console.log(parms)
    this.setState({
      sort:parms
    })
    this.getData()
  };
  onFormSearch(values){
    this.setState({
      pageData:{pageNo:1,pageSize:10}
    },()=>{
      this.getData(values)
    })
  }
  render() {
    const { columns, dataSource, pageData, total, form_show, searchOption, newColumns, isModalVisible, isModalOpen } = this.state;
    return (
      <div className="p-layout-box">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton size="middle" type="primary" haspermi={['marketingTool:bargainBlackList:setting']} onClick={() => this.hardSetting()}>难度配置</TheButton>
        </TheTableExtend>
        <TheTable
          scroll={{ x: "max-content", y: '63vh' }}
          columns={newColumns}
          dataSource={dataSource}
          onChange={this.handleTableChange}
        />
        <ThePagination pageNo={pageData.pageNo} pageSize={pageData.pageSize} total={total} pageChange={this.pageChange} />
        <Modal title={'加入黑名单'} visible={isModalVisible} footer={null} onCancel={() => this.handleCancel()} width="30%">
          <Form ref={this.formRef}
            onFinish={(values) => this.handleOk(values)}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 12,
            }}
          >
            <Form.Item
              name="blacklistRemark"
              label='备注'
              rules={[{ required: true }]}>
              <TextArea placeholder="加入黑名单理由" style={{ height: 120 }} />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        <Modal title={'难度配置'} visible={isModalOpen} footer={null} onCancel={() => this.settingCancel()} width="30%">
          <Form ref={this.addFormRef}
            onFinish={(values) => this.settingOk(values)}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 12,
            }}
          >
            <Form.Item
              name="platformSetShowValue"
              label='砍价倍数'
              rules={[{ required: true }]}>
              <Input type="number" placeholder="普通用户的倍数"/>
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="default" onClick={() => this.settingCancel()} style={{ 'marginRight': 20 }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
